package sdk

import (
	"context"
	"fmt"
	"gim-server/config"
	"gim-server/utils"
	"github.com/go-redis/redis"
	"sync"
	"time"
)

var (
	rds     *redis.Client
	rdsOnce sync.Once
)

func Redis(ctx context.Context) *redis.Client {
	rdsOnce.Do(func() {
		var err error
		cnf := config.GetCfg()
		if cnf.RedisPass != "" {
			cnf.RedisPass, err = utils.AesDe(cnf.RedisPass, cnf.SignKey)
			if err != nil {
				panic(fmt.Errorf("解密mysql密码(%v)错误！", cnf.RedisPass))
			}
		}
		rds = redis.NewClient(&redis.Options{
			Addr:         cnf.RedisUrl,
			Password:     cnf.RedisPass,
			DB:           cnf.RedisDB,
			MinIdleConns: 30,
			MaxConnAge:   time.Second * time.Duration(100),
			DialTimeout:  time.Second * time.Duration(10),
			ReadTimeout:  time.Second * time.Duration(10),
			WriteTimeout: time.Second * time.Duration(10),
			IdleTimeout:  time.Second * time.Duration(10),
		})
		err = rds.Ping().Err()
		if err != nil {
			panic(err)
		}
	})
	return rds.WithContext(ctx)
}
